<template>
  <div style="border: 1px solid red">
    <h1>计数：{{ count }}</h1>
    <button @click="countAdd">count增加</button>
    <h1>计数：{{ num }}</h1>
    <button @click="numAdd">num增加</button>
    <h1>加载顺序：setup函数--beforeCreate--data函数--created</h1>
  </div>

  <br />

  <div style="border: 1px solid green">
    <h1>用户名：{{ user.username }}</h1>
    <h1>用户名：{{ username }}</h1>
    <h1>reverseType:{{ reverseType }}</h1>
    <h1>特点：{{ type }}</h1>
    <button @click="changeType">修改特点</button>
  </div>

  <br />

  <MySetup :uname="username" :uage="age" class="abc"></MySetup>
</template>

<script>
// 引入ref和reactive
// toRefs把对象转换为单独的
// computed计算属性
// watchEffect监听
// provide\inject提供和注入，用于父子组件传值
import {
  ref,
  reactive,
  toRefs,
  computed,
  watchEffect,
  watch,
  provide,
} from "vue";

import MySetup from "./components/demo_setup.vue";

export default {
  name: "App",
  data() {
    return {
      count: 0,
    };
  },
  setup() {
    // 基本数据类型用ref，引用数据类型用reactive
    const num = ref(1);
    function numAdd() {
      // 值保存在value中
      num.value += 10;
    }

    const user = reactive({
      username: "小明",
      age: 18,
      type: "handsome",
      reverseType: computed(() => {
        return user.type.split("").reverse().join("");
      }),
    });
    function changeType() {
      user.type = "超级帅";
    }

    // 监听变化的回调函数
    // 广泛、主动监听
    watchEffect(() => {
      console.log("watchEffect函数里用到的依赖改变时才会触发");
      console.log(user.type);
      // console.log(num.value);
    });

    // 针对性、惰性监听
    watch(num, (newval, oldval) => {
      console.log("old", oldval);
      console.log("new", newval);
    });

    const student = reactive({
      stuname: "小白",
      stuclass: "三年一班",
    });
    provide("student", student);

    // ...toRefs(user)解构user中的每个属性
    return { num, user, numAdd, changeType, ...toRefs(user) };
  },
  methods: {
    countAdd() {
      this.count++;
      this.num++;
    },
  },
  components: {
    MySetup,
  },
};
</script>
